package com.qhx.rtkcloud.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test1 {

    public static void main(String[] args) {
        mockSocket(11011);
    }

    public static void mockSocket(int port)  {
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1", port);
            InputStream inputStream =  socket.getInputStream();
            OutputStream outputStream =  socket.getOutputStream();
            //
            Executors.newScheduledThreadPool(1)
                    .scheduleAtFixedRate(() -> {
            try {
                outputStream.write((port + "send message").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
//                        }
                    }, 1,1, TimeUnit.SECONDS);
              //  outputStream.write((port + "send message").getBytes());



            new Thread(() -> {
                byte[] bytes = new byte[1024];
                int length = 0;

                try {
                    while ((length = inputStream.read(bytes)) > 0)  {
                        System.out.println(port + "receive msg " + new String(Arrays.copyOfRange(bytes, 0, length)));
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }





            }).start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (port == 1011) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}